package com.midcent.networklib.utils.logger;

import android.os.Environment;
import android.util.Log;
import com.midcent.networklib.manager.HttpRequestNetManager;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtils {
	private static final String TAG = "WNBLogger";

	/** 是否提示debug信息，正式版本为false */
	public static boolean DEBUG = true;
//	public static boolean DEBUG = true;
	private static final boolean WRITE_SDCARD_LOG = HttpRequestNetManager.isdebug;
	private static final String WRITE_SDCARD_FOLD = "WorkNetBank";
	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"MM-dd HH:mm:ss ms");

	// 异常日志大小限制在5M
	private static final float ERR_LOG_SIZE = 5000 * 1024.0f;

	private LogUtils() {
	}

	private synchronized static String buildMsg(String msg) {
		StringBuilder buffer = new StringBuilder();
		Date date = new Date();
		String time = sdf.format(date);

		buffer.append(time);
		final StackTraceElement stackTraceElement = Thread.currentThread()
				.getStackTrace()[4];
		buffer.append(" [");
		buffer.append(Thread.currentThread().getName());
		buffer.append(":");
		buffer.append(stackTraceElement.getFileName());
		buffer.append(":");
		buffer.append(stackTraceElement.getLineNumber());
		buffer.append(":");
		buffer.append(stackTraceElement.getMethodName());
		buffer.append("()] ");
		buffer.append(msg);
		buffer.append("\n");
		return buffer.toString();
	}

	public static void v(String msg) {
		if (DEBUG) {
			Log.v(TAG, buildMsg(msg));
		}
	}

	public static void v(String tag, String msg) {
		if (DEBUG) {
			Log.v(tag, buildMsg(msg));
		}
	}

	public static void d(String msg) {
		if (DEBUG) {
			Log.d(TAG, buildMsg(msg));
		}
	}

	public static void d(String tag, String msg) {
		if (DEBUG) {
			Log.d(tag, buildMsg(msg));
		}
	}

	public static void i(String msg) {
		if (DEBUG) {
			Log.i(TAG, buildMsg(msg));
		}
	}

	public static void i(String tag, String msg) {
		if (DEBUG) {
			Log.i(tag, buildMsg(msg));
		}
	}

	public static void w(String msg) {
		String info = buildMsg(msg);
		Log.w(TAG, info);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info);
		}
	}

	public static void w(String tag, String msg) {
		String info = buildMsg(msg);
		Log.w(tag, info);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info);
		}
	}

	public static void w(String msg, Exception e) {
		String info = buildMsg(msg);
		Log.w(TAG, info, e);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info + getStackTrace(e));
		}
	}

	public static void w(String tag, String msg, Exception e) {
		String info = buildMsg(msg);
		Log.w(tag, info, e);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info + getStackTrace(e));
		}
	}

	public static void e(String msg) {
		String info = buildMsg(msg);
		Log.e(TAG, info);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info);
		}
	}

	public static void e(String tag, String msg) {
		String info = buildMsg(msg);
		Log.e(tag, info);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info);
		}
	}

	public static void e(String msg, Exception e) {
		String info = buildMsg(msg);
		Log.e(TAG, info, e);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info + getStackTrace(e));
		}
	}

	public static void e(String tag, String msg, Exception e) {
		String info = buildMsg(msg);
		Log.e(tag, info, e);

		if (WRITE_SDCARD_LOG) {
			writeFileToSD(info + getStackTrace(e));
		}
	}

	/**
	 * 将内容写入文件
	 * @param content
	 */
	private static void writeFileToSD(String content) {
		RandomAccessFile raf = null;
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			Log.d(TAG, "SD card is not avaiable right now.");
			return;
		}
		try {
			String fodlerName = WRITE_SDCARD_FOLD;
			String pathName = Environment.getExternalStorageDirectory()
					+ File.separator + fodlerName + File.separator;// 在SD卡上目录名称
			String fileName = "normal_warnning.log";
			File path = new File(pathName);
			File file = new File(pathName + fileName);
			if (!path.exists()) {
				if (path.mkdir()) {
					Log.d(TAG, "Created the path:" + pathName);
				}
			}
			if (!file.exists()) {
				if (file.createNewFile()) {
					Log.d(TAG, "Create the new file:" + fileName);
				} else {
					Log.d(TAG, fileName + " has existed!");
				}
			}

			raf = new RandomAccessFile(file, "rw");
			if (file.length() > ERR_LOG_SIZE) {
				raf.seek(0);
			} else {
				raf.seek(file.length());
			}

			raf.write(content.getBytes());
		} catch (Exception e) {
			Log.e(TAG, "Error to write SD card.");
		} finally {
			if (null != raf) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取异常函数栈
	 * @param t
	 * @return
	 */
	public static String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		t.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}
}
